﻿using DocumentFormat.OpenXml.Office2010.Excel;
using Domain.Material_Management;
using Domain.Production_Modules;
using Infratructure.Interface;
using MediatR;
using MES.Server.API.Application.Command.Production_Modules;
using MES.Server.API.Dto.Warehouse;
using ReturnValue;

namespace MES.Server.API.Application.Handler.Production_Modules
{
    public class GetMaterialsOutInHander : IRequestHandler<GetMaterialsOutInCommand, ApiPaging<GetMaterialsOutInDTO>>
    {
        private readonly IRepository<MaterialOutInModel> materialOutInRepo;
        private readonly IRepository<ProductMaterialsModel> productMaterialsRepo;
        public GetMaterialsOutInHander(IRepository<MaterialOutInModel> materialOutInRepo, IRepository<ProductMaterialsModel> productMaterialsRepo)
        {
            this.materialOutInRepo = materialOutInRepo;
            this.productMaterialsRepo = productMaterialsRepo;
        }
        /// <summary>
        /// 出入库记录表
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<ApiPaging<GetMaterialsOutInDTO>> Handle(GetMaterialsOutInCommand request, CancellationToken cancellationToken)
        {
           var result = new ApiPaging<GetMaterialsOutInDTO>();
           var materialOutIn = materialOutInRepo.GetAll();
            var productMaterials = productMaterialsRepo.GetAll();
            var linq = from m in materialOutIn
                       join p in productMaterials on m.ProductMaterialsId equals p.Id
                       select new GetMaterialsOutInDTO
                       {
                         Id = m.Id,
                        OutInCode = m.OutInCode,
                        OutIn = m.OutIn,
                        OutInCount = m.OutInCount,
                        ProductMaterialsId = p.Id,
                        ProductMaterialsName =p.ProductMaterialsName,
                        MaterialAskCode = m.MaterialAskCode,
                        CreaterPeople = m.CreaterPeople,
                        CreateTime = m.CreateTime,
                       };
            if(request.OutIn!=null)
            {
                linq = linq.Where(x => x.OutIn == request.OutIn);
            }
            if(!string.IsNullOrEmpty(request.ProductMaterialsName))
            {
                linq = linq.Where(x => x.ProductMaterialsName.Contains(request.ProductMaterialsName));
            }
            result.TotalPage = linq.OrderByDescending(x => x.CreateTime).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();
            result.Totalcount = linq.Count();
            result.Code = StatusCode.Success;
            return Task.FromResult(result);
        }
    }
}
